<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-16 18:35:00
 * @Last Modified time: 2023-02-17 16:32:13
 */
namespace app\api\controller\store;	
use think\facade\App;
use app\common\services\store\GoodsCommentService;
use app\common\services\store\OrderGoodsService;
use frank\services\FileUploadService;

/**
 * Class GoodsComment
 */
class GoodsComment extends \app\api\controller\Base
{ 	
    /**
     * GoodsCommentService constructor.
     * @param App $app
     */
    public function __construct(App $app,GoodsCommentService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * @method(GET)
     */
    public function order(){
        $orderId = $this->request->param('order_id');
        // 验证订单是否已完成
        if (!$this->service->checkOrderAllowComment($orderId)) {
            $this->error($this->service->getError());
        }

        // 待评价商品列表
        $goodsList = $this->service->getNotCommentGoodsList($orderId);
        if ($goodsList->isEmpty()) {
            $this->error('该订单没有可评价的商品');
        }
        $this->success(compact('goodsList'));
    }

    /**
     * 评论提交
     * @method(POST)
     */
    public function create(){
        $data = $this->request->getMore([
            ['order_id', ''],
            ['formData', ''],
        ]);
        $formData = $this->formatFormData($data['formData']);
        $fileService = FileUploadService::instance();
        foreach ($formData as $key => &$item) {
            if(!empty($item['imgs'])){
                // 缓存图片移到指定目录
                $item['imgs'] = $fileService->moveCacheFiles($item['imgs'],'comments');
            }
        }
        // 
        if ($this->service->createForOrder($this->uid,$data['order_id'],$formData)) {
            $this->success('评价成功');
        }
        $this->error($this->service->getError() ?: '评价失败');
    }

    /**
     * 格式化 formData
     * @param string $formJsonData
     * @return array
     */
    public function formatFormData($formJsonData)
    {
        return array_column(json_decode($formJsonData, true), null, 'order_goods_id');
    }
}